﻿using System;

namespace Traceroute
{
	internal class IcmpHeader
	{
		private const int HEADER_SIZE = 8;
		private byte _code;
		private byte _type;

		public byte Type
		{
			get { return _type; }
			set { _type = value; }
		}

		public byte Code
		{
			get { return _code; }
			set { _code = value; }
		}

		public byte[] PackData(byte[] data)
		{
			var result = new byte[HEADER_SIZE + data.Length];
			int index = 0;
			result[0] = _type;
			result[1] = _code;
			Array.Copy(data, 0, result, HEADER_SIZE, data.Length);
			ushort checkSum = GetCheckSum(result);
			byte[] byteCheckSum = BitConverter.GetBytes(checkSum);
			result[2] = byteCheckSum[0];
			result[3] = byteCheckSum[1];
			return result;
		}

		public static ushort GetCheckSum(byte[] data)
		{
			ulong checksum = 0;
			int newLenght = ((data.Length + 1)/2)*2;
			var newData = new byte[newLenght];
			Array.Copy(data, newData, data.Length);

			for (int i = 0; i < newLenght; i += 2)
			{
				checksum += BitConverter.ToUInt16(newData, i);
			}
			checksum = (checksum >> 16) + (checksum & 0xffff);
			checksum += (checksum >> 16);
			return (ushort) (~checksum);
		}
	}
}